"use client"
// @/components/MessageContext.tsx
import { createContext, useContext, useState, ReactNode, useCallback } from 'react';
import { Modal } from '@/app/component/model';

// 消息配置类型
type MessageOptions = {
  id: string;
  header: ReactNode;
  content: ReactNode;
};

// 上下文类型
type MessageContextType = {
  messages: MessageOptions[];
  showMessage: (options: Omit<MessageOptions, 'id'>) => void;
  closeMessage: (id: string) => void;
};

// 创建上下文
const MessageContext = createContext<MessageContextType | undefined>(undefined);

// 提供者组件（需要包裹整个应用）
export function MessageProvider({ children }: { children: ReactNode }) {
  const [messages, setMessages] = useState<MessageOptions[]>([]);

  // 显示消息：添加到队列
  const showMessage = useCallback((options: Omit<MessageOptions, 'id'>) => {
    const id = Date.now().toString(); // 生成唯一ID
    setMessages(prev => [...prev, { ...options, id }]);
  }, []);

  // 关闭消息：从队列移除
  const closeMessage = useCallback((id: string) => {
    setMessages(prev => prev.filter(msg => msg.id !== id));
  }, []);

  return (
    <MessageContext.Provider value={{ messages, showMessage, closeMessage }}>
      {children}
      {/* 渲染所有消息（关键：将消息组件挂载到DOM） */}
      {messages.map(msg => (
        <Modal
          key={msg.id}
          open={true} // 始终为true，通过移除队列控制关闭
          onOpenChange={(open) => !open && closeMessage(msg.id)}
          header={msg.header}
          content={msg.content}
        />
      ))}
    </MessageContext.Provider>
  );
}

// 自定义Hook：用于获取消息方法
export function useMessage() {
  const context = useContext(MessageContext);
  if (!context) throw new Error('useMessage must be in MessageProvider');
  return context.showMessage;
}